package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
@RequestMapping("employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 登录功能
     *
     * @param employee
     * @return
     */
    @PostMapping("login")
    public R login(@RequestBody Employee employee) {
        //1.将前端提交的密码进行MD5加密处理
        String password = employee.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.根据前端页面提供的用户名查询数据库
        LambdaQueryWrapper<Employee> lqw = Wrappers.<Employee>lambdaQuery();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee employee1 = employeeService.getOne(lqw);
        //3.如果没有查询到则返回登陆失败结果
        if (employee1 == null) {
            return R.error("用户名不存在");
        }
        //4.密码比对，如果不一致则返回登录失败结果
        if (!md5Password.equals(employee1.getPassword())) {
            return R.error("用户名或密码错误");
        }
        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (employee1.getStatus() == 0) {
            return R.error("用户已被禁用");
        }
        //6.登录成功，将员工id存入Session并返回登录成功结果
        httpServletRequest.getSession().setAttribute("employee", employee1.getId());
        return R.success(employee1);
    }

    /**
     * 登出功能
     *
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout() {
        //销毁session（下面两种方法作用相同）
        httpServletRequest.getSession().removeAttribute("employee");//根据键删除
        //httpServletRequest.getSession().invalidate();
        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //设置初始密码，进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //对新增员工的数据进行校验，账户中不能包含空格
        String trim = employee.getUsername().trim();
        employee.setUsername(trim);
        if (trim.contains(" ")) {
            return R.error("账户不能包含空格");
        }
        //设置创建时间，修改时间
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        /*//设置创建人，修改人
        Long creat = (Long) httpServletRequest.getSession().getAttribute("employee");
        employee.setUpdateUser(creat);
        employee.setCreateUser(creat);*/
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("查询页码：{}，每页条数：{}，姓名：{}", page, pageSize, name);
        //构造分页构造器
        Page<Employee> page1 = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> el = Wrappers.<Employee>lambdaQuery();
        //添加过滤条件（模糊查询）
        el.like(!StringUtils.isEmpty(name), Employee::getName, name);
        //添加排序条件
        el.orderByDesc(Employee::getCreateTime);
        //执行查询方法
        employeeService.page(page1, el);
        return R.success(page1);
    }

    /**
     * 启用/禁用员工账号
     *
     * @param employee
     * @return
     */
   /* @PutMapping
    public R<String> update(@RequestBody Employee employee) {
       *//* log.info(employee.toString());
        System.out.println(employee.toString());
        //设置修改时间和修改的人
        Long employee1 = (Long) httpServletRequest.getSession().getAttribute("employee");
        employee.setUpdateUser(employee1);
        employee.setUpdateTime(LocalDateTime.now());
        //调用方法进行修改
        boolean b = employeeService.updateById(employee);
        System.out.println(b);
        return R.success("修改成功");*//*
        log.info(employee.toString());

        Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }*/
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
   /*     Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);*/
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    /**
     * 根据id修改员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getByid(@PathVariable Long id) {
        log.info("根据id查询员工信息");
        Employee byId = employeeService.getById(id);
        //判断是否为空
        if (byId != null) {
            return R.success(byId);
        }
        return R.error("没有查询到员工信息");
    }

}
